<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="入库编号" prop="bpsSn">
        <el-input
          v-model="queryParams.bpsSn"
          placeholder="请输入入库编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:put_storage:add']"
        >新增入库单</el-button>
      </el-col>
      <!--          <el-col :span="1.5">-->
      <!--            <el-button-->
      <!--              type="success"-->
      <!--              plain-->
      <!--              icon="el-icon-edit"-->
      <!--              size="mini"-->
      <!--              :disabled="single"-->
      <!--              @click="handleUpdate"-->
      <!--              v-hasPermi="['mes:put_storage:edit']"-->
      <!--            >修改</el-button>-->
      <!--          </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:put_storage:export']"
        >导出</el-button>
      </el-col>
      <!--          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="put_storageList" border style="width: 100%"@selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" :width="55" align="center" />-->
      <!--          <el-table-column label="序号" align="center" prop="number" />-->
      <el-table-column label="状态" align="center" prop="state" >
        <template v-slot = "scope">
          <dict-tag :options="dict.type.storage_put_status" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="入库类型" align="center" prop="bpsType">
        <template v-slot = "scope">
          <dict-tag :options="dict.type.storage_bpstype" :value="scope.row.bpsType"/>
        </template>
      </el-table-column>
      <el-table-column label="车间任务编号" align="center" prop="taskSn" />
      <el-table-column label="产品名称" align="center" prop="proName" />
      <el-table-column label="入库单编号" align="center" prop="bpsSn" />
      <el-table-column label="需入库数量" align="center" prop="bpsNum" />
      <el-table-column label="已入库数量" align="center" prop="bpsRenum" />
      <el-table-column label="入库日期" align="center" prop="bpsDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.bpsDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createdBy" />
      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:put_storage:edit']"
          >入库</el-button>
          <!--              <el-button-->
          <!--                size="mini"-->
          <!--                type="text"-->
          <!--                icon="el-icon-delete"-->
          <!--                @click="handleDelete(scope.row)"-->
          <!--                v-hasPermi="['mes:put_storage:remove']"-->
          <!--              >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改入库管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-divider v-if="title=='完工入库确认'" >仓库信息</el-divider><!--分割线-->
        <el-row v-if="title=='完工入库确认'">
          <el-col :span="12">
            <el-form-item label="成品库" prop="strmId">
              <el-select v-model="form.strmId" placeholder="请选择仓库" @change="handleStrmChange">
                <el-option
                  v-for="item in storeroomList"
                  :key="item.id"
                  :label="`${item.name}/${item.sn}`"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库容量" prop="capacity" label-width="auto">
              <el-row type="flex" align="middle">
                <el-col :span="12">
                  <span>总容量:{{form.strmNum}}</span>
                </el-col>
                <el-col :span="12">
                  <span>可用容量:{{form.strmNum-form.strmRenum}}</span>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider>成品列表</el-divider><!--分割线-->
        <el-form-item label="车间任务编号" prop="orderId" label-width="120px">
          <el-select v-if="title=='添加入库单'" v-model="form.taskId" placeholder="请选择车间任务" @change="handleTaskChange" >
            <el-option
              v-for="item in taskList"
              :key="item.id"
              :label="`${item.name}/${item.sn}`"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-select v-else v-model="form.taskId" placeholder="请选择车间任务" :disabled="true">
            <el-option
              v-for="item in taskList"
              :key="item.id"
              :label="`${item.name}/${item.sn}`"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-card shadow="always" style="border-radius: 15px;">
          <el-table border style="width: 100%" v-loading="loading" :data="taskProList">
            <el-table-column label="产品名称" prop="proName">
            </el-table-column>
            <el-table-column label="产品编码" prop="proSn">
            </el-table-column>
            <el-table-column v-if="title=='添加入库单'" label="需入库数量">
              <template slot-scope="scope">
                <el-input-number id="inputNumber" v-model:value="form.bpsNum" :min="0" :max="10" :precision="2"/>
              </template>
            </el-table-column>
            <el-table-column v-else label="入库数量">
              <template slot-scope="scope">
                <el-input-number id="inputNumber" v-model:value="form.num" :min="0" :max="form.bpsNum-form.bpsRenum" :precision="2"/>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addPut_storage,
  delPut_storage,
  getPut_storage,
  listPut_storage,
  updatePut_storage,
  updateWaf,
} from "@/api/mes/put_storage";
import {listStoreroom} from "@/api/mes/storeroom";
import {listTask} from "@/api/mes/task";

export default {
  name: "warehousingAsFinished",
  dicts:["storage_put_status","storage_bpstype"],
  // name: "child1",
  data() {
    return {
      // 默认第一个选项卡
      activeName: 'first',
      // 初始化两个变量 isChildUpdate1:true，isChildUpdate2:false；
      // 使用v-if控制child1和child2是否渲染。
      // 每次切换tab选项的时候，触发事件。让当前点击的tab变量设置位true，让当前组件重新渲染。
      // 这时候当你来回切换的时候，通过v-if判断是否重新渲染当前组件
      isChildUpdate2: true,
      isChildUpdate3: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库管理表格数据
      put_storageList: [],
      //库房列表
      storeroomList:[],
      //车间任务列表
      taskList:[],
      //车间任务产品列表
      taskProList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bpsSn: null,
      },
      queryParamsStrm: {
        sn: null,
        name: null,
      },
      queryParamsTask: {
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getStrmList();
    this.getTaskList();
  },
  methods: {
    handleStrmChange(){
      this.form.strmId=parseInt(this.form.strmId)
      const selectedStrm = this.storeroomList.find(option => option.id === this.form.strmId);
      if (selectedStrm) {
        // 更新其他输入框的值
        this.form.strmNum = selectedStrm.strmNum;
        this.form.strmRenum = selectedStrm.strmRenum;
      }
    },

    handleTaskChange(){
      this.form.taskId=parseInt(this.form.taskId)
      this.taskProList = this.taskList.filter(option => option.id == this.form.taskId);
      this.form.proStrmId=this.taskProList[0].proId;
      console.log("this.form",this.form)
    },

    /** 查询入库管理列表 */
    getList() {
      this.loading = true;
      const bpsType = 1;
      listPut_storage(this.queryParams).then(response => {
        this.put_storageList = response.rows;
        this.put_storageList = this.put_storageList.filter(item => item.bpsType == bpsType)
        console.log(this.put_storageList)
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询入库管理列表 */
    getStrmList() {
      this.loading = true;
      listStoreroom(this.queryParamsStrm).then(response => {
        this.storeroomList = response.rows;
        const strmType = 1;
        this.storeroomList = this.storeroomList.filter(item => item.strmType == strmType)
      });
    },
    /** 查询入库管理列表 */
    getTaskList() {
      this.loading = true;
      listTask(this.queryParamsTask).then(response => {
        this.taskList = response.rows;
      });
    },


    // /** 计算列表编号 */
    // calculateIndex() {
    //   this.put_storageList.forEach((item, index) => {
    //     this.$set(item, 'number', index + 1);
    //   });
    // },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        bpsSn: null,
        proStrmId: null,
        bpsNum: null,
        bpsRenum:0,
        num:0,
        bpsType: null,
        bpsDate: null,
        isDeleted: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedDate: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加入库单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPut_storage(id).then(response => {
        this.form = response.data;
        this.form.num=0;
        this.handleTaskChange();
        this.open = true;
        this.title = "完工入库确认";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.bpsType=1;
      console.log("dadwdad",this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            if((this.form.bpsRenum+this.form.num)<this.form.bpsNum){
              this.form.state=1;
            }
            else{
              this.form.state=2;
            }
            this.form.bpsRenum=this.form.bpsRenum+this.form.num;
            // updatePut_storage(this.form).then(response => {
            //   this.$modal.msgSuccess("修改成功");
            //   this.open = false;
            //   this.getList();
            // });
            console.log("dadada")
            updateWaf(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPut_storage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除入库管理编号为"' + ids + '"的数据项？').then(function() {
        return delPut_storage(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/put_storage/export', {
        ...this.queryParams
      }, `put_storage_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>


